package com.yyq.adms.hngg.action;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.hngg.bpo.PeriodicalMagazineBpo;
import com.yyq.adms.hngg.pojo.MagazineDetail;
import com.yyq.adms.hngg.pojo.PeriodicalMagazine;
import com.yyq.adms.usermanage.pojo.RecordSentDep;
import com.yyq.adms.util.JxlsUtil;
import com.yyq.adms.util.JxlsVo;
import com.yyq.adms.util.ValidateUtil;
import com.yyq.adms.util.ValidateVo;
import com.yyq.adms.yyb.advance.pojo.STApply;
import com.yyq.adms.yyb.advance.pojo.STReport;
import com.yyq.adms.yyb.paper.pojo.PublishPaper;
import com.yyq.adms.yyb.summary.pojo.TechnologyReport;
import com.yyq.adms.zz.pojo.Writings;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.util.ObjectUtil;
import com.yyq.sos.util.PermissionsUtil;

@Controller("periodicalMagazineAction")
@Scope("prototype")
public class PeriodicalMagazineAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PeriodicalMagazine po = new PeriodicalMagazine();
	private PeriodicalMagazineBpo bpo;
	private String isUpdatePage;
	private List accessoryList;
	private String tempmsg = "";
	private String footMsg = "";

	public List getAccessoryList() {
		return accessoryList;
	}

	public void setAccessoryList(List accessoryList) {
		this.accessoryList = accessoryList;
	}

	public String getIsUpdatePage() {
		return isUpdatePage;
	}

	public void setIsUpdatePage(String isUpdatePage) {
		this.isUpdatePage = isUpdatePage;
	}

	/**
	 * 参数，代表查询的期数
	 */
	private String param;

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	private Map _map = new HashMap();

	@Resource(name = "periodicalMagazineBpo")
	public void setBpo(PeriodicalMagazineBpo bpo) {
		bpo.setCls(po.getClass());
		this.bpo = bpo;
	}

	public PeriodicalMagazineBpo getBpo() {
		return bpo;
	}

	public PeriodicalMagazine getPo() {
		return po;
	}

	public void setPo(PeriodicalMagazine po) {
		this.po = po;
	}

	@Override
	public String execute() throws Exception {
		super.setObj(po);
		super.setBpo(bpo);
		if (null != isUpdatePage && !"".equals(isUpdatePage)) {
			setCmd("update");
		}
		String ret = super.execute();
		po = (PeriodicalMagazine) getObj();
		return ret;
	}

	@Override
	public String add() {
		return super.add();
	}

	@Override
	public String data() {
		LoginUser user = (LoginUser) this.getSession().getAttribute(
				Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this
				.getSession(), moduleName, Constants.RIGHT_GLOBAL);

		String hql = "";
		if (user.getUserId().intValue() == 1 || isPerm) {
			hql = "FROM PeriodicalMagazine ORDER BY years DESC,createdate DESC";
		} else {
			hql = "from PeriodicalMagazine obj where obj.maintainDep="
					+ user.getOrgId()
					+ " or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId and rsd.yyqTableName='"
					+ bpo.getTableName(po.getClass()) + "' and rsd.sentDepId="
					+ user.getOrgId()
					+ ")   ORDER BY obj.years DESC,obj.createdate DESC";
		}
		// setData(bpo.search(sql));
		
		String periodicalPageNoStr = (String)this.getSession().getAttribute("periodicalPageNo");
		if(null != periodicalPageNoStr && !periodicalPageNoStr.equals("")) {
			Integer periodicalPageNo = Integer.valueOf(periodicalPageNoStr);
			getPageForm().setPageNo(periodicalPageNo.intValue());
		}
		this.getSession().removeAttribute("periodicalPageNo");
		
		this.setFormData(bpo.searchPage(hql, getPageForm().getPageNo(),
				getPageForm().getPageSize()));
		List _dataList = this.getData();
		accessoryList = new ArrayList();
		for (int i = 0; i < _dataList.size(); i++) {
			PeriodicalMagazine _periodical = (PeriodicalMagazine) _dataList
					.get(i);
			hql = "from Accessory where sourceRecordId = "
					+ _periodical.getId()
					+ " and yyqTableName='periodicalmagazine'";
			List _temperaryList = bpo.search(hql);
			if (null != _temperaryList && _temperaryList.size() > 0) {
				for (int j = 0; j < _temperaryList.size(); j++) {
					accessoryList.add(_temperaryList.get(j));
				}

			}
		}

		return ActionType.ACTION_DATA_LIST;
	}

	@Override
	public String update() {
		PeriodicalMagazine _obj = (PeriodicalMagazine) getObj();
		String hql = "update periodicalmagazinedetail d set d.years = '"
				+ _obj.getYears() + "' , d.magazineName = '"
				+ _obj.getMagazineName() + "' where d.belongParentID = "
				+ _obj.getId();
		this.getBpo().execSql(hql);
		return super.update();
	}

	public Map get_map() {

		List _list = this.getData();
		for (int i = 0; i < _list.size(); i++) {
			PeriodicalMagazine _source = (PeriodicalMagazine) _list.get(i);
			String year = _source.getYears();
			if (_map.get(year) != null) {
				((List) _map.get(year)).add(_source);
			} else {
				_map.put(year, new ArrayList());
				((List) _map.get(year)).add(_source);
			}
		}
		return _map;
	}

	public void set_map(Map map) {
		_map = map;
	}

	@Override
	public String search() {
		//Object _obj = getObj();
		//setObj(new MagazineDetail());
		String searchProperty = ((String[])this.getFormValue("searchProperty"))[0];
		String searchKey = ((String[])this.getFormValue("searchKey"))[0];
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			if("sentDep".equals(searchProperty)){
				hql = "select distinct obj from MagazineDetail obj,RecordSentDep rsd,SysDepts d where " +
					  " obj.id=rsd.sourceRecordId and rsd.sentDepId=d.id and rsd.yyqTableName='periodicalmagazinedetail' and d.deptCname like '%"+searchKey+"%' order by years desc,magazineName asc";
			}else{
				hql = "from MagazineDetail obj where obj."+searchProperty+" like '%"+searchKey+"%' order by years desc,magazineName asc";
			}
		}else{
			hql = "from MagazineDetail obj where (obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId  and rsd.yyqTableName='periodicalmagazinedetail'  and rsd.sentDepId="+user.getOrgId()+"))  and obj."+searchProperty+" like '%"+searchKey+"%' order by years desc,magazineName asc";
		}
		System.out.println("hql============================>\n"+hql);
		this.setFormData(bpo.searchPage(hql, this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		//setObj(_obj);
		List _dataList = this.getData();
		accessoryList = new ArrayList();
		if(null != _dataList && _dataList.size() > 0 ) {
			for(int i = 0; i < _dataList.size(); i ++) {
				MagazineDetail _periodical = (MagazineDetail) _dataList.get(i);
				hql = "from Accessory where sourceRecordId = " + _periodical.getBelongParentID()
				+ " and yyqTableName='periodicalmagazine'";
				List _temperaryList = bpo.search(hql);
				if (null != _temperaryList && _temperaryList.size() > 0) {
					for (int j = 0; j < _temperaryList.size(); j++) {
						accessoryList.add(_temperaryList.get(j));
					}
				}
			}
		}
		return "dataSearch";
	}

	@Override
	public String goAdd() {
		super.mainList();
		return super.goAdd();
	}

	@Override
	public String goUpdate() {
		super.mainList();
		return super.goUpdate();
	}

	@Override
	public String batchAdd() {
		Object _obj = getObj();
		setNeedBatchAddParent(true);
		setObj(new MagazineDetail());
		//   start

		if(this.getAccessory() != null){
			String msg = "";
			String updatePage = ((String[])this.getFormMap().get("updatePage"))[0];
			if("xls".equals(this.getAccessoryFileName().substring(this.getAccessoryFileName().lastIndexOf(".")+1))){
				try {
					List<Map<String, JxlsVo>> srcData = JxlsUtil.getInstance().transfromData(this.getAccessory(),2);
					List<MagazineDetail> targetData = new ArrayList<MagazineDetail>();
					LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
					List<Map<String, JxlsVo>> otherOrgRepeatData = new ArrayList<Map<String, JxlsVo>>(); 
					Map<String,Object> vMap = new LinkedHashMap<String, Object>();
					msg = bpo.validateBatchAdd(srcData, targetData,vMap,user,otherOrgRepeatData);
					if(msg.toString().equals("") && otherOrgRepeatData.size()==0){
						if(targetData.size()>0){
							targetData = processBatchAddParent(targetData);
							Serializable[] ids = bpo.save(targetData.toArray());
							if(ids != null){
								msg = "{processId:\"1\",msg:\"批量导入成功!\"}";
							}else{
								//msg = "{processId:\"1\",msg:\"批量导入失败!\"}";
								if(!updatePage.equals("YES")){
									Long parentID = Long.valueOf(((String[])this.getFormMap().get("sourceRecordId"))[0]);
									bpo.delete(parentID);
									//msg = "{processId:\"5\",msg:\"" + msg +"\"}";
								}
								msg = "{processId:\"1\",msg:\"批量导入出错,请检查导入的文档格式及数据是否正确!\"}";
							}
							this.getSession().setAttribute("msg", msg);
						}else{
							this.getSession().setAttribute("msg", msg);
						}
					}else{
						//msg = "{processId:\"5\",msg:\"本次新建的期刊及提交的论文列表均未新建(导入),请修改后重新提交！\"}";
						this.getSession().setAttribute("msg", msg);
						//并且在此处删除信息
						//假如是新增的，则删除，修改的则不做任何处理
						
						if(updatePage.equals("NO")){
							Long parentID = Long.valueOf(((String[])this.getFormMap().get("sourceRecordId"))[0]);
							bpo.delete(parentID);
							msg = "{processId:\"5\",msg:\"" + msg +"\"}";
						} else {
							//msg = "{processId:\"5\",msg:\"本次提交的论文列表均未导入,请修改后重新提交！\"}";
							msg = "{processId:\"5\",msg:\"" + msg +"\"}";
						}
						
					}
				} catch (Exception e) {
					if(!updatePage.equals("YES")){
						Long parentID = Long.valueOf(((String[])this.getFormMap().get("sourceRecordId"))[0]);
						bpo.delete(parentID);
						//msg = "{processId:\"5\",msg:\"" + msg +"\"}";
					}
					msg = "{processId:\"1\",msg:\"批量导入出错,请检查导入的文档格式及数据是否正确!\"}";
					this.getSession().setAttribute("msg", msg);
					e.printStackTrace();
				}
				this.setMsg(msg);
			}else{
				this.setMsg("{processId:\"1\",msg:\"文件类型不支持!\"}");
				this.getSession().setAttribute("msg", msg);
			}
			String isYes = ((String[])getFormMap().get("updatePage"))[0];
			if(isYes != null && isYes.equals("YES")) {
				footMsg = "本次提交的论文列表未导入，请修改后重新提交！";
			} else {
				footMsg = "本次新建的期刊及提交的论文列表均未新建(导入)，请修改后重新提交！";
			}
			
			this.getSession().setAttribute("footMsg", footMsg);
			
		}
		//   end
		//String result = super.batchAdd();
		setObj(_obj);
		//return result;
		return ActionType.ACTION_MSG;

	}
	
	@Override
	public String showBatchAddMsg() {
		this.setData(new ArrayList());
		this.setMsg((String)this.getSession().getAttribute("msg"));
		this.getSession().removeAttribute("msg");
		this.getSession().removeAttribute("vMap");
		this.getSession().removeAttribute("repeatData");
		this.getSession().removeAttribute("repeatKey");
		return "periodicalBatchAddErrorMsg";
	}
	
	
	
	
	

	@Override
	public List processBatchAddParent(List list) {
		for (int i = 0; i < list.size(); i++) {
			MagazineDetail _detail = (MagazineDetail) list.get(i);
			if (null != getFormMap().get("parentID")) {
				_detail.setBelongParentID(Integer
						.valueOf(((String[]) getFormMap().get("parentID"))[0]));
			} else {
				_detail
						.setBelongParentID(Integer
								.valueOf(((String[]) getFormMap().get(
										"sourceRecordId"))[0]));
			}
			_detail.setYears(((String[]) getFormMap().get("year"))[0]);
			_detail.setMagazineName(((String[]) getFormMap()
					.get("magazineName"))[0]);
		}
		return list;

	}
	

}
